Python Package Documentation

Python Package Documentation - External API

This chapter provides information on eCognition's external Python API. This external package is accessible based on the Python program itself by installing the ecognitionapi package using the appropriate wheel package.

Installation files for external Python API - eCognition wheel packages

Python versions supported for the ecognitionapi are versions 3.8 to 3.12.

Commands for installation of wheel packages:

Exemplary Python scripts - see below.

This chapter covers only the external API - an embedded eCognition API is provided based on the algorithm 'python script' using Python files in inline scripts. See Embedded Python API Reference.htm.

Class EcognitionApi

Class for eCognition engine API. Used to create and analyze eCognition projects via rule sets.

Special methods EcognitionApi

__init__(log_file_path, license_server)

Initialize and start the eCognition engine.

Parameters:

log_file_path: str Log file path.

license_server: Optional[str] = None
Server where license is located. The following strings are accepted:
{port}@{ip}, @{ip}, {ip}.
If the port is not specified the default port 27000 is used.
If ip is not specified, then localhost is used.

Raises:

EcognitionException If an error occurs.

__enter__()

A method used for EcognitionApi context management. Enables the use of EcognitionApi in a with statement.

Returns:

EcognitionApi Returns: eCogntionApi instance, that can be used in a with statement.

__exit__(*args)

Used for EcognitionApi context management. This method will call EcognitionApi.shutdown() method, when exiting a with statement.

Methods EcognitionApi

shutdown()

Shutdown the eCognition engine.

Raises:

EcognitionException If an error occurs.

version()

eCogntion engine version.

Returns:

str Version string.

add_image(img_path, layer_name, map_name)

Add an image to the eCognition project.

Parameters:

img_path: str Image file path.

layer_name: Optional[str] = None
Name of the added image layer. If None, then default name is used.

map_name: Optional[str] = None
Name of the layer map. If None, then default map is used.

Raises:

EcognitionException

If an error occurs.

add_thematic(thm_path, attr_path, layer_name, map_name)

Add a thematic layer to the eCognition project.

Parameters:

thm_path: str Thematic layer file path.

attr_path: str Attribute file path.

layer_name: Optional[str] = None
Name of the added image layer. If None, then default name is used.

map_name: Optional[str] = None
Name of the layer map. If None, then default map is used.

Raises:

EcognitionException If an error occurs.

add_point_cloud(pc_path, layer_name, map_name)

Add a point cloud to the eCognition project. This method is available on Windows only.

Parameters:

pc_path: str Point cloud file path.

layer_name: Optional[str] = None
Name of the added point cloud layer. If None, then default name is used.

map_name: Optional[str] = None
Name of the layer map. If None, then default map is used.

Raises:

NotImplementedError If used on non Windows machine.

EcognitionException If an error occurs.

get_point_cloud_classes(layer_name, map_name)

Get a list of point cloud classes. This method is available on Windows only.

Parameters:

layer_name: Optional[str] = None
Name of the point cloud layer.

map_name: Optional[str] = None
Name of the layer map. If None, then default map is used.

Raises:

NotImplementedError If used on non Windows machine.

EcognitionException If an error occurs.

Returns:

list[int] List of point cloud classes.

add_camera_image(camera_images, camera_info, layer_name, map_name)

Add camera images with camera information to the eCognition project.

Parameters:

camera_images: Sequence[CameraImage]
Sequence of camera image paths and frame information.

camera_info: CameraInformation
Camera information that all frames share.

layer_name: Optional[str] = None
Name of the added image layer. If None, then default name is used.

map_name: Optional[str] = None
Name of the layer map. If None, then default map is used.

Raises:

EcognitionException If an error occurs.

create_project()

Create an eCognition project. Must be called before EcognitionApi.analyze can be called.

Raises:

EcognitionException If an error occurs during project creation.

create_project_set_size(llx, lly, res, size_x, size_y)

Create a project (main map) with specified position, resolution and size.

Parameter:

LLX: float Geo x coordinate of the lower left pixel of the project (main map).

LLY: float Geo y coordinate of the lower left pixel of the project (main map).

res: float Pixel resolution in meters.

size_x: int Project size x in pixels.

size_y: int Project size y in pixels.

Raises:

EcognitionException If an error occurs.

save_project(project_path)

Save an eCognition project to a specified path.

Parameter:

project_path: str Path to save the project.

Raises:

EcognitionException If an error occurs.

close_project()

Close an eCognition project and release used memory.

Raises:

EcognitionException If an error occurs.

add_map_set_size(map_name, llx, lly, res, size_x, size_y)

Add a new map to the eCognition project.

Parameter:

map_name: str
Name of the map to add, the name cannot be 'main'.

LLX: float
Geo x coordinate of the lower left pixel of the map.

LLY: float
Geo y coordinate of the lower left pixel of the map.

res: float Pixel resolution in meters.

size_x: int Map size x in pixels.

size_y: int Map size y in pixels.

Raises:

EcognitionException If an error occurs.

load_ruleset(ruleset_path)

Load rule set to the eCognition project.

Parameter:

ruleset_path: str File path to the rule set.

Raises:

EcognitionException If an error occurs.

 

analyze(process_id)

Run an analysis using the loaded rule set.

Parameter:

process_id: str
Rule set process ID. An entry point of the rule set for the analysis.

Raises:

EcognitionException If an error occurs during analysis.

 

get_variable_value_float(variable_name)

Get a float variable value from the eCognition project.

Parameter:

variable_name: str The name of the variable.

Returns:

float A value associated with the variable.

Raises:

EcognitionException
If a variable with the given name does not exist, or if some other error occurs.

 

get_variable_value_str(variable_name)

Get a string variable value from the eCognition project.

Parameter:

variable_name: str The name of the variable.

Returns:

str A value associated with the variable.

Raises:

EcognitionException
If a variable with the given name does not exist, or if some other error occurs.

 

set_variable_value(variable_name, variable_value)

Set a variable value in the eCognition project.

Parameter:

variable_name: str The name of the variable.

variable_value: Union[float, str] A new value for the variable.

Raises:

EcognitionException If an error occurs.

 

get_array_float(array_name)

Get a float array from the eCognition project.

Parameter:

array_name: str The name of the array.

Returns:

list[float] A list of values associated with the array.

Raises:

EcognitionException
If an array with the given name does not exist, or if some other error occurs.

set_array(array_name, array_values)

Set array values in the eCognition project.

Parameter:

array_name: str The name of the array.

array_values: Union[Sequence[float], Sequence[str]]
A sequence of values for the array.

Raises:

EcognitionException If an error occurs.

 

get_vector_layer(layer_name, map_name)

Get a vector layer with a given name.

Parameter:

layer_name: str Name of the vector layer to get.

map_name: Optional[str] = None
Name of the layer map. If None, then default map is used.

Returns:

VectorLayer A vector layer.

Raises:

EcognitionException If an error occurs.

 

create_vector_layer(layer_name, vector_type, map_name)

Create a new vector layer with a given name.

Parameter:

layer_name: str New vector layer name.

vector_type: VectorType Type of the new vector layer.

map_name: Optional[str] = None
Name of the layer map. If None, then default map is used.

Returns:

VectorLayer Created vector layer.

Raises:

EcognitionException If an error occurs.

set_deep_learning_cpu_only(cpu_only)

Set whether Tensorflow should use only CPU.

Parameter:

cpu_only: bool Whether Tensorflow should use only CPU.

Returns:

bool The previous value of the flag.

Raises:

EcognitionException If an error occurs.

set_cancel_analyze()

Set the flag to cancel the analysis.

Raises:

EcognitionException If an error occurs.

reset_ruleset()

Reset the loaded ruleset.

Raises:

EcognitionException If an error occurs.

Class VectorLayer

Class for eCognition vector layer.

Methods - Properties VectorLayer

name

Returns vector layer name of type string.

Returns:

str Returns vector layer name of type string.

vector_type

Returns vector layer type.

Returns:

VectorType Returns vector layer type.

is_3d_type

Returns True if the vector layer is 3D type, False otherwise.

Returns:

bool Returns True if the vector layer is 3D type, False otherwise.

Methods VectorLayer

get_attribute_definitions()

Get attribute names and types of the vector layer.

Returns:

list[tuple[str, AttributeType]]
List of attribute definitions - name and type.

Raises:

EcognitionException If an error occurs.

get_attribute_count()

Get the number of attributes of the vector layer.

Returns:

int The number of attributes in integer format.

Raises:

EcognitionException If an error occurs.

get_vector_count()

Get the number of vectors in the vector layer.

Returns:

int The number of vectors.

Raises:

EcognitionException If an error occurs.

get_vector(vector_idx)

Get a vector from the vector layer.

Parameter:

vector_idx: int The vector index.

Returns:

Union[VectorPoint, VectorLine, VectorPolygon]
A vector depending on the vector layer type.

Raises:

EcognitionException If an error occurs.

add_attribute_definition(attribute_name, attribute_type)

Add an attribute definition to the vector layer. This method must be called before adding vectors to the vector layer.

Parameter:

attribute_name: str Name of the attribute.

attribute_type: AttributeType Type of the attribute.

Raises:

EcognitionException If an error occurs.

add_vector(
points: Sequence[tuple[float, float]],
attr_val: Sequence[Union[float, str]],
holes: Optional[Sequence[Sequence[tuple[float, float]]]])

Add a 2D vector with attribute values to the vector layer.

Parameter:

points: Sequence[tuple[float, float]]
Vector points. Cannot be empty.

attr_val: Sequence[Union[float, str]]
Attribute values. Must be in the same order as attribute definitions were created. Must be equal to the number of attributes.

holes: Optional[Sequence[Sequence[tuple[float, float]]]]
Vector holes. If vector type is not polygon, then it must be equal to None.

Raises:

EcognitionException If an error occurs.

add_vector(
points: Sequence[tuple[float, float, float]],
attr_val: Sequence[Union[float, str]],
holes: Optional[Sequence[Sequence[tuple[float, float, float]]]])

Add a 3D vector with attribute values to the vector layer.

Parameter:

points: Sequence[tuple[float, float, float]]
Vector points. Cannot be empty.

attr_val: Sequence[Union[float, str]]
Attribute values. Must be in the same order as attribute definitions were created. Must be equal to the number of attributes.

holes: Optional[Sequence[Sequence[tuple[float, float, float]]]]
Vector holes. If vector type is not polygon, then it must be equal to None.

Raises:

EcognitionException If an error occurs.

Class VectorType

Type of the vector layer geometry.

Parameter:

Point2D: VectorType 2D point vector type.

Line2D: VectorType 2D line vector type.

Polygon2D: VectorType 2D polygon vector type.

Point3D: VectorType 3D point vector type.

Line3D: VectorType 3D line vector type.

Polygon3D: VectorType 3D polygon vector type.

Class AttributeType

Type of the vector layer attribute.

Parameter:

Double: AttributeType Double attribute type.

String: AttributeType String attribute type.

Class VectorPoint

An eCognition vector point class.

Methods VectorPoint

is_3d_type

Returns True if the vector layer is 3D type, False otherwise.

Returns:

bool Returns True if the vector layer is 3D type, False otherwise.

get_attributes()

Get attribute name to value dictionary.

Returns:

dict[str, Union[float, str]] Attribute name to value dictionary.

Raises:

EcognitionException If an error occurs.

get_point_count()

Get the number of points in vector.

Returns:

int The number of points.

Raises:

EcognitionException If an error occurs.

points()

Generator that yields points of the vector.

Yields:

Union[Generator[tuple[float, float], None, None],
Generator[tuple[float, float, float], None, None]

Vector points. Tuple depends on the vector type.

Raises:

EcognitionException If an error occurs.

get_point()

Get a single point of the vector.

Returns:

Union[tuple[float, float], tuple[float, float, float]]
Vector point. Tuple depends on the vector type.

Raises:

EcognitionException If an error occurs.

Class VectorLine

An eCognition vector line class.

Methods VectorLine

is_3d_type

Returns True if the vector layer is 3D type, False otherwise.

Returns:

bool Returns True if the vector layer is 3D type, False otherwise.

get_attributes()

Get attribute name to value dictionary.

Returns:

dict[str, Union[float, str]] Attribute name to value dictionary.

Raises:

EcognitionException If an error occurs.

get_point_count()

Get the number of points in vector.

Returns:

int The number of points.

Raises:

EcognitionException If an error occurs.

points()

Generator that yields points of the vector.

Yields:

Union[Generator[tuple[float, float], None, None],
Generator[tuple[float, float, float], None, None]

Vector points. Tuple depends on the vector type.

Raises:

EcognitionException If an error occurs.

Class VectorPolygon

An eCognition vector point class.

Methods VectorPolygon

is_3d_type

Returns True if the vector layer is 3D type, False otherwise.

Returns:

bool Returns True if the vector layer is 3D type, False otherwise.

get_attributes()

Get attribute name to value dictionary.

Returns:

dict[str, Union[float, str]] Attribute name to value dictionary.

Raises:

EcognitionException If an error occurs.

get_point_count()

Get the number of points in vector.

Returns:

int The number of points.

Raises:

EcognitionException If an error occurs.

points()

Generator that yields points of the vector.

Yields:

Union[Generator[tuple[float, float], None, None],
Generator[tuple[float, float, float], None, None]

Vector points. Tuple depends on the vector type.

Raises:

EcognitionException If an error occurs.

get_hole_count()

Get the number of inner holes in the vector.

Returns:

int The number of inner holes.

Raises:

EcognitionException If an error occurs.

get_hole_point_count(hole_idx)

Get the number of points in the inner hole.

Returns:

hole_idx: int Inner hole index.

Raises:

EcognitionException If an error occurs.

get_hole_points(hole_idx)

Generator that yields points of the inner vector hole.

Yields:

hole_idx: Union[Generator[tuple[float, float], None, None],
Generator[tuple[float, float, float], None, None]

Inner hole index. Tuple depends on the vector type.

Raises:

EcognitionException If an error occurs.

Class CameraFrameInformation

Camera information for each individual frame.

Parameter:

x: float x camera position in meters.

y: float y camera position in meters.

z: float z camera position in meters.

roll: float Camera orientation in degrees.

pitch: float Camera orientation in degrees.

heading: float Camera orientation in degrees.

__init__(x, y, z, roll, pitch, heading)

Parameter:

x: float x camera position in meters.

y: float y camera position in meters.

z: float z camera position in meters.

roll: float Camera orientation in degrees.

pitch: float Camera orientation in degrees.

heading: float Camera orientation in degrees.

Class CameraRotationOrder

The order of camera rotations.

Parameter:

HPR: CameraRotationOrder Heading, pitch, roll order.

HRP: CameraRotationOrder Heading, roll, pitch order.

RPH: CameraRotationOrder Roll, pitch, heading order.

PRH: CameraRotationOrder Pitch, roll, heading order.

Class CameraCoordinateSystem

The coordinate system the camera uses.

Parameter:

TMX: CameraCoordinateSystem TMX coordinate system.

 

Class CameraImage

Camera image with camera frame information.

Parameter:

image_path: str Camera image file path.

info: CameraFrameInformation Camera frame information.

__init__(image_path, info)

Parameter:

image_path: str Camera image file path.

info: CameraFrameInformation Camera frame information.

Class CameraInformation

Camera information that all frames share.

Parameter:

pixel_size_x: float x dimension of a single pixel of the CCD sensor in meters.

pixel_size_y: float y dimension of a single pixel of the CCD sensor in meters.

width: float Camera resolution.

height: float Camera resolution.

focal_length_x: float Focal length in the x direction. This value is normalized by the pixel size.

focal_length_y: float Focal length in the y direction. This value is normalized by the pixel size.

principal_point_x: float x coordinate of the principal point.

principal_point_y: float y coordinate of the principal point.

rotation_order: CameraRotationOrder The order that camera rotations should be applied in.

coordinate_system: CameraCoordinateSystem The coordinate system the camera uses.

__init__(pixel_size_x, pixel_size_y, width, height, focal_length_x, focal_length_y, principal_point_x, principal_point_y, rotation_order, coordinate_system)

Parameter:

pixel_size_x: float x dimension of a single pixel of the CCD sensor in meters.

pixel_size_y: float y dimension of a single pixel of the CCD sensor in meters.

width: float Camera resolution.

height: float Camera resolution.

focal_length_x: float Focal length in the x direction. This value is normalized by the pixel size.

focal_length_y: float Focal length in the y direction. This value is normalized by the pixel size.

principal_point_x: float x coordinate of the principal point.

principal_point_y: float y coordinate of the principal point.

rotation_order: CameraRotationOrder The order that camera rotations should be applied in.

coordinate_system: CameraCoordinateSystem The coordinate system the camera uses.

Python External API Examples

In the following examples we introduce some basic approaches using eCognitions external API. The examples are installed together with the installation of eCognition Developer in <eCognition Developer installation directory>\bin\examples\python-external-api.

Overview

Precondition to use the examples:

Example - simple_processing_example.py

In this example an image in loaded and analyzed based on a simple rule set. The example shows the following main steps:

Copy
import ecognitionapi as ecog
import os

# control logging level: "Nothing" / "Basic" / "Detailed" / "Everything"
os.environ["ECOG_CONFIG_logging"]="trace level=Basic"


def simple_project_example():
    print("-----------------------------------------------")
    print("Example: simple image/rule set execution pipeline. Load image and run rule set")

    # create eCognition API
    ecogApi = ecog.EcognitionApi(log_file_path=os.path.abspath("logs/engine.log"), license_server="@localhost")
    # load rule set
    ecogApi.load_ruleset(os.path.abspath("rulesets/multi-resolution.dcp"))
     # add image
    ecogApi.add_image(img_path = os.path.abspath("data/Landast.tif"))
    # create a project
    ecogApi.create_project()
    # execute branch of the ruleset specified explicitly: separating parent nodes with double slash (//)
    # to execute all processes from the ruleset, specify: ""
    ecogApi.analyze("do//segmentation")

    # save the project
    ecogApi.save_project(os.path.abspath("results/project.dpr"))
    # close the project
    ecogApi.close_project()
    # shutdown API
    ecogApi.shutdown()


if __name__ == "__main__":
    simple_project_example()

 

Example - variable_example.py

This example demonstrates how to pass parameters to rule set using Scene variables. It also demonstrates how a result value can be retrieved after the analysis using Scene variables. The example shows the following main steps:

Copy
import ecognitionapi as ecog
import os

# control logging level: "Nothing" / "Basic" / "Detailed" / "Everything"
os.environ["ECOG_CONFIG_logging"]="trace level=Basic"



def variable_example():
    '''
    This example demonstrates how to pass parameters to rule set using Scene variables
    It also demonstrates how result value can be retrieved after analysis using Scene variables
    '''

    print("-----------------------------------------------")
    print(f"Example: how to set input variable parameter and get output variable from the ruleset.")

    # create eCognition API
    ecogApi = ecog.EcognitionApi(log_file_path=os.path.abspath("logs/engine.log"), license_server="@localhost")

    # load rule set
    ecogApi.load_ruleset(os.path.abspath("rulesets/multi-resolution.dcp"))
     # add image
    ecogApi.add_image(img_path = os.path.abspath("data/Landast.tif"))
    # create a project
    ecogApi.create_project()

    # set parameters to the rule set
    # here we set Scene variable (specified in the ruleset) that will control output path for export statistics .csv
    export_dir = os.path.abspath("results")
    print(f"setting input parameters: output_folder and multi-resolution segmentation scale")
    ecogApi.set_variable_value("output_folder", export_dir)
    ecogApi.set_variable_value("var_Scale", 100)

    # run rule set
    ecogApi.analyze("do")

    # get the analysis result
    result = ecogApi.get_variable_value_float("result_avg_obj_size")
    print(f"getting result: result_avg_obj_size={result}")

    # close the project
    ecogApi.close_project()
    # shutdown API
    ecogApi.shutdown()


if __name__ == "__main__":
    variable_example()

Example - array_example.py

This example demonstrates how to pass array parameters to a rule set and how to retrieve a result array after the analysis.

The example shows the following main steps:

Copy
import ecognitionapi as ecog
import os

# control logging level: "Nothing" / "Basic" / "Detailed" / "Everything"
os.environ["ECOG_CONFIG_logging"]="trace level=Basic"


def array_example():
    '''
    This example demonstrates how to pass array parameters to rule set
    and how to retrieve result array after analysis is finished
    '''

    print("-----------------------------------------------")
    print(f"Example: how to set input array parameter and get output array from the ruleset.")

    # create eCognition API
    ecogApi = ecog.EcognitionApi(log_file_path=os.path.abspath("logs/engine.log"), license_server="@localhost")

    # load rule set
    ecogApi.load_ruleset(os.path.abspath("rulesets/arrays.dcp"))
     # add image
    ecogApi.add_image(img_path = os.path.abspath("data/Landast.tif"))
    # create a project
    ecogApi.create_project()

    # set input array
    arr_sizes = [i for i in range(20,25)]
    ecogApi.set_array("arr_Sizes", arr_sizes)

    # run rule set
    ecogApi.analyze("")

    # get the analysis result
    print("after multi-resolution segmentation here are number of objects per size:")
    num_objs = ecogApi.get_array_float("arr_NumberOfObjects")
    for i in range(len(num_objs)):
        print(f"size {arr_sizes[i]} pxls: #objects={int(num_objs[i])}")

    # close the project
    ecogApi.close_project()
    # shutdown API
    ecogApi.shutdown()


if __name__ == "__main__":
    array_example()

Example - pointcloud_example.py

This example demontrates how to apply a simple point cloud processing. Note that point cloud processing is currently only supported for Windows OS. The example shows the following main steps:

Copy
import ecognitionapi as ecog
import os

# control logging level: "Nothing" / "Basic" / "Detailed" / "Everything"
os.environ["ECOG_CONFIG_logging"]="trace level=Basic"


def pointcloud_example():
    '''
    This example demonstrates point cloud processing. Windows OS only!
    '''

    print("-----------------------------------------------")
    print(f"Example: how to add and process point clouds. Windows OS only!")

    # create eCognition API
    ecogApi = ecog.EcognitionApi(log_file_path=os.path.abspath("logs/engine.log"), license_server="@localhost")

    # load rule set
    ecogApi.load_ruleset(os.path.abspath("rulesets/pointcloud_classification.dcp"))

    # add point cloud
    ecogApi.add_point_cloud(pc_path="data/pointcloud.las", )
    # create project
    ecogApi.create_project()

    # set export directory
    output_dir = os.path.abspath("results")
    ecogApi.set_variable_value("output_folder", output_dir)

    # run rule set
    ecogApi.analyze("")

    # close the project
    ecogApi.close_project()
    # shutdown API
    ecogApi.shutdown()

if __name__ == "__main__":
    pointcloud_example()

Example - vector_example.py

This example demontrates how to dynamically create and add vectors to a project. The example consists of the following main steps:

Copy
import ecognitionapi as ecog
import os

# control logging level: "Nothing" / "Basic" / "Detailed" / "Everything"
os.environ["ECOG_CONFIG_logging"]="trace level=Basic"

def vectors_example():
    '''
    This example demonstrates how to dynamically create and add vectors to the project
    '''

    print("-----------------------------------------------")
    print(f"Example: how to create vectors in eCognition project dynamically.")

    # create eCognition API
    ecogApi = ecog.EcognitionApi(log_file_path=os.path.abspath("logs/engine.log"), license_server="@localhost")


    # load rule set
    ecogApi.load_ruleset(os.path.abspath("rulesets/vectors.dcp"))
    # create empty project without geocoding
    ecogApi.create_project_set_size(0,0,1,1000,1000)

    # create simple 2D polygon with a hole
    vector_layer = ecogApi.create_vector_layer(layer_name="test_polygon", vector_type=ecog.VectorType.Polygon2D)
    vector_layer.add_attribute_definition("test_attribute", ecog.AttributeType.String)
    vector_layer.add_vector(points=[(100,100),(100,900),(900,900),(900,100),(100,100)], \
                            attr_val=["some_attr_value"], \
                            holes=[[(400,400),(400,600),(600,600),(600,400)]])

    # create sample 2D point layer with 4 points
    vector_layer = ecogApi.create_vector_layer(layer_name="test_points", vector_type=ecog.VectorType.Point2D)
    vector_layer.add_vector(points=[(100,100),(100,900),(900,900),(900,100)], attr_val=[])

    # create sample 2D line layer with 1 line
    vector_layer = ecogApi.create_vector_layer(layer_name="test_lines", vector_type=ecog.VectorType.Line2D)
    vector_layer.add_vector(points=[(100,100),(900,900)], attr_val=[])

    # set export directory
    output_dir = os.path.abspath("results")
    ecogApi.set_variable_value("output_folder", output_dir)

    # run rule set
    ecogApi.analyze("")

    # close the project
    ecogApi.close_project()

    # shutdown API
    ecogApi.shutdown()


if __name__ == "__main__":
    vectors_example()

Example - maps_example.py

This example demonstrates the creation of a second map in a project and how to add data to that map. The worker map can be created explicitly as described in the code below or it will be created implicitly by 'add_image' call with the map_name parameter.

The example consists of the following main steps:

Copy
import ecognitionapi as ecog
import os

# control logging level: "Nothing" / "Basic" / "Detailed" / "Everything"
os.environ["ECOG_CONFIG_logging"]="trace level=Basic"

def maps_example():
    '''
    This example demonstrates creation of second map in the project and 
    adding data to that map. The worker map can be created explicitly as in the code below
    or it will be created implicitly by 'add_image' call with map_name parameter
    '''
    print("-----------------------------------------------")
    print(f"Example: how to create maps in eCognition project dynamically.")


    # create eCognition API
    ecogApi = ecog.EcognitionApi(log_file_path=os.path.abspath("logs/engine.log"), license_server="@localhost")

    # create empty project without geocoding (unused)
    ecogApi.create_project_set_size(0,0,1,100,100)

    # map2: create empty map 'map2' with the predefined size
    ecogApi.add_map_set_size("map2",0,0,1,1544,1506)
    # map2: add image, but map size remains as specified above
    ecogApi.add_image(img_path = os.path.abspath("data/Landast.tif"), layer_name="Layer 1", map_name="map2")
    # map2: add vector, 2D line layer
    vector_layer = ecogApi.create_vector_layer(layer_name="test_lines", vector_type=ecog.VectorType.Line2D, map_name="map2")
    vector_layer.add_vector(points=[(0,0),(1544,1506)], attr_val=[])

    # save project
    ecogApi.save_project(os.path.abspath("results/maps_example.dpr"))
    # close the project
    ecogApi.close_project()

    # shutdown API
    ecogApi.shutdown()


if __name__ == "__main__":
    maps_example()

 

 

 

For more information see also:

 

Embedded Python eCognition API:

Installation Guide > Windows > Python Installation - installation and setup

Reference Book > Algorithms and Processes > Miscellaneous > Python Script - description algorithm and its parameters

Reference Book > Algorithms and Processes > Miscellaneous > Embedded Python API Reference - reference for each class, properties and methods

User Guide > Python Integration - application examples for python scripts and Debugging python code in eCognition Developer